package cn.exrick.xboot.base.serviceimpl

import cn.exrick.xboot.base.entity.*
import cn.exrick.xboot.base.mapper.ExamResultConfirmCheckMapper
import cn.exrick.xboot.base.service.*
import cn.exrick.xboot.core.common.utils.PageUtil
import cn.exrick.xboot.core.common.utils.ResultUtil
import cn.exrick.xboot.core.common.utils.SecurityUtil
import cn.exrick.xboot.core.common.utils.ToolUtil
import cn.exrick.xboot.core.common.vo.PageVo
import cn.exrick.xboot.core.common.vo.Result
import cn.exrick.xboot.core.service.UserService
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.google.common.collect.Maps
import lombok.extern.slf4j.Slf4j
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.math.BigDecimal
import java.util.*

/**
 * 考试监督员考试结果确认审核接口实现
 * @author Fei
 */
@Slf4j
@Service
@Transactional
open class IExamResultConfirmCheckServiceImpl : ServiceImpl<ExamResultConfirmCheckMapper?, ExamResultConfirmCheck?>(), IExamResultConfirmCheckService {


    @Autowired
    private lateinit var iEmployeeOfficialExamRecordService: IEmployeeOfficialExamRecordService

    @Autowired
    private lateinit var iExamConfirmCheckService: IExamConfirmCheckService

    @Autowired
    private lateinit var securityUtil: SecurityUtil

    @Autowired
    private lateinit var iInformService: IInformService

    @Autowired
    private lateinit var userService: UserService

    @Autowired
    private lateinit var iEnterpriseEmployeeRecordService: IEnterpriseEmployeeRecordService

    @Autowired
    private lateinit var iEmployeeExamStatusService: IEmployeeExamStatusService

    @Autowired
    private lateinit var iExamPassEmployeeService: IExamPassEmployeeService

    override fun createExamResultConfirmCheck(examSelPic: String?): Result<Any?>? {

        //1.判断监考员有没有确认考试审核
       return iEmployeeOfficialExamRecordService.getMyEmployeeOfficialExamLast()?.run {


            if (!iExamConfirmCheckService.getExamConfirmCheckStatusByOfficialId(id)!!) {

                return ResultUtil.error(201, "监考员还未确认考试信息")
            }

            //2. 更新考试记录表考试自拍照信息
            examSelfPic = examSelPic
            iEmployeeOfficialExamRecordService.updateById(this)

            //3. 添加审核信息
            save(ExamResultConfirmCheck().apply {

                officialExamRecordId = this@run.id
                supervisionUserId = this@run.supervisionUserId
            })

           return ResultUtil.success("提交审核信息成功！")
        } ?: ResultUtil.error("请把手机提交给监考人员进行验证！")

    }

    override fun getMyExamResultConfirmCheckList(pageVo: PageVo, checkStatus: Int?): Result<MutableMap<String, Any?>?>? {


        return ToolUtil.setListToNul(list(KtQueryWrapper(ExamResultConfirmCheck::class.java)
                .eq(ExamResultConfirmCheck::supervisionUserId, securityUtil.currUser.id)
                .eq(ToolUtil.isNotEmpty(checkStatus), ExamResultConfirmCheck::checkStatus, checkStatus)
                .orderByDesc(ExamResultConfirmCheck::createTime)))?.run {

            val result: MutableMap<String, Any?> = Maps.newHashMap()
            result["size"] = size
            result["content"] = PageUtil.listToPage(pageVo, mapNotNull {
                iEmployeeOfficialExamRecordService.getEmployeeOfficialExamVo(it!!.officialExamRecordId!!)
                        ?.apply { id = it.id }
            })

            ResultUtil.data(result, "获取考试审核列表成功！")
        } ?: ResultUtil.error(201, "暂无数据！")

    }

    override fun checkExamResultConfirm(examResultConfirmCheck: ExamResultConfirmCheck): Result<Any?>? {


        return getById(examResultConfirmCheck.id)?.run {


            checkStatus = examResultConfirmCheck.checkStatus
            checkReason = examResultConfirmCheck.checkReason
            checkUserId = securityUtil.currUser.id
            updateById(this)

            when (examResultConfirmCheck.checkStatus) {

                 2 -> {

                     //1. 消息通知
                     iInformService.save(Inform().apply {

                         title = "考试结果审核通知"
                         content = "尊敬的".plus(userService.get(this@run.createBy)?.nickname).plus("员工您好").plus(",你参加的企业培训正式考试通过审核!")
                         informType = 2
                         informToUserId = this@run.createBy
                     })

                     iEmployeeOfficialExamRecordService.getById(this@run.officialExamRecordId)?.let {
                     //2. 考试记录
                     iEnterpriseEmployeeRecordService.save(EnterpriseEmployeeRecord().apply {



                             jobTrainId = it.jobTrainId
                             jobTrainPartId = it.jobTrainPartId
                             TestType = 2
                             TestScore = 100
                             completeTrain = true
                             createBy = this@run.createBy
                         })

                         //3.考试状态
                         iEmployeeExamStatusService.getOne(KtQueryWrapper(EmployeeExamStatus::class.java)
                                 .eq(EmployeeExamStatus::jobTrainId, it.jobTrainId)
                                 .eq(EmployeeExamStatus::createBy, this@run.createBy))?.let { employeeExamStatus ->

                             employeeExamStatus.endTime = Date()
                             employeeExamStatus.completeProcess = BigDecimal(employeeExamStatus.completeProcess!!).add(BigDecimal(1)).toInt()
                             if (employeeExamStatus.completeProcess == 5) {

                                 employeeExamStatus.completeTraining = true
                             }
                             iEmployeeExamStatusService.updateById(employeeExamStatus)
                         }

                         //4. 记录考试通过表
                         iExamPassEmployeeService.save(ExamPassEmployee().apply {

                             enterpriseId = it.enterpriseId
                             employeeUserId = it.employeeUserId
                             officialExamRecordId = it.id
                         })
                     }

                }
                else -> {

                    //1. 消息通知
                    iInformService.save(Inform().apply {

                        title = "考试结果审核通知"
                        content = "尊敬的".plus(userService.get(createBy)?.nickname).plus("员工您好").plus(",你参加的企业培训正式考试审核失败!")
                                .plus("失败原因是:").plus(examResultConfirmCheck.checkReason)
                        informType = 2
                        informToUserId = this@run.createBy
                    })
                }
            }

            return ResultUtil.success("操作成功!")
        } ?: ResultUtil.error(201, "不存在此条审核记录")
    }

}